package cn.hx.controller;

import cn.hx.entity.Dept;
import cn.hx.entity.News;
import cn.hx.entity.User;
import cn.hx.service.DeptService;
import cn.hx.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class NewsController {
    @Autowired
    NewsService newsService;

    @GetMapping("searchNews")
    public ModelAndView getSearchDept() {
        ModelAndView modelAndView = new ModelAndView("searchNews");
        modelAndView.addObject("news",newsService.findAll());
        return modelAndView;
    }
    @GetMapping("createNews")
    public String getCreateNews(){
        return "createNews";
    }

    //    修改回显
    @GetMapping("updateNews/{id}")
    public String getUpdateDept(@PathVariable Integer id, Model model){
        model.addAttribute("news",newsService.queryById(id));
        return "updateNews";
    }
    //    修改
    @PostMapping("editNews/{id}")
    public String getEditDept(@PathVariable Integer id, News news){
        news.setId(id);
        news.setCreateTime(new Date());
        newsService.update(news);
        return "redirect:/searchNews";
    }
    //    删
    @GetMapping("deleteNews/{id}")
    public String getDeleteDept(@PathVariable Integer id){
        newsService.deleteById(id);
        return "redirect:/searchNews";
    }
    //    增
    @PostMapping("saveNews")
    public String postSaveNews(News news, HttpSession session){
        User user =(User) session.getAttribute("loginUser");
        news.setUser(user);
        news.setUserId(user.getId());
        newsService.insert(news);
        return "redirect:/searchNews";
    }

}
